package cn.u313.comm.utils;


import cn.u313.entry.JiLuEntry;
import cn.u313.entry.UserEntry;
import com.alibaba.fastjson.JSON;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {
    public static HashMap<String,Integer> map=new HashMap<>();
    public static HashMap<String,Integer> zengsong=new HashMap<>();
    public static HashMap<String,Integer> qixi=new HashMap<>();
    public static HashMap<String,Integer> yu=new HashMap<>();
    public static HashMap<String,Integer> chiyu=new HashMap<>();
    public static HashMap<String,Integer> chiyuType=new HashMap<>();
    public static HashMap<String,Integer> mota=new HashMap<>();
    public static HashMap<String,Integer> motaType=new HashMap<>();
    public static HashMap<String,Integer> cardZhuangzheng=new HashMap<>();
    public static long TimerMoyu;
    private static String 火="♪";
    private static String 玫瑰="[CAT:face,face=63,id=63]";
    private static String 太阳="[CAT:face,face=318,id=318]";
    static public String icon=太阳;
    static public String iconXQ="[CAT:face,id=137]";
    static public String icon0=火;
    //    public static boolean isFish=false;
    public static int fish=0;//yude shulia      ng
    public static boolean sendJson=true;//是否json
    public static boolean isDaJieAdmin=false;//是否json
    public static boolean cehui = false;
    public static boolean 闪照 = false;
    private static String icon1="http://gchat.qpic.cn/gchatpic_new/1054980699/1127256559-2424065923-C06ED8501E3D284A6F05F71A90E69F3F/0?term=2";
    private static String icon2="http://gchat.qpic.cn/gchatpic_new/1054980699/1127256559-2424065923-C06ED8501E3D284A6F05F71A90E69F3F/0?term=2";
    public static void log(String str){
        System.err.println(str);
    }
    public static boolean isYuanDang(){
        int aa= getTime(0);
        return (aa>=20210101&&aa<=20210103);
    }
    public static String json(String a,String title,String text){
        String str="{\"app\":\"com.tencent.qqpay.qqmp.groupmsg\",\"desc\":\"\",\"view\":\"groupPu" +
                "shView\",\"ver\":\"1.0.0.7\",\"prompt\":\"%s\",\"appID\":\"\",\"sourceName\":\"\",\"act" +
                "ionData\":\"\",\"actionData_A\":\"\",\"sourceUrl\":\"\",\"meta\":{\"groupPushData\":{\"t" +
                "ime\":\"\",\"cancel_url\":\"http:\\/\\/www.baidu.com\",\"fromIcon\":\"\",\"report" +
                "_url\":\"https:\\/\\/kf.qq.com\\/faq\\/"+Math.random()+".html\",\"bannerLink\"" +
                ":\"\",\"fromName\":\"name\",\"summaryTxt\":\"%s\",\"bannerIm" +
                "g\":\""+icon2+"\",\"bannerTxt\":\"%s\",\"item1Img\":\"\"}},\"config\":{\"for" +
                "ward\":0,\"showSender\":1},\"text\":\"qtxml.cn\",\"extraApps\":[],\"sourceAd\":\"\"}";
        return a(String.format(str,new String[]{a,text,title}));
    }
    public static String json1(String title,String text){
        String json="{\"app\":\"com.tencent.qqpay.qqmp.groupmsg\",\"d" +
                "esc\":\"\",\"view\":\"groupPushView\",\"ver\":\"1." +
                "0.0.7\",\"prompt\":\"%s\",\"meta\":{\"groupPu" +
                "shData\":{\"time\":\"\",\"cancel_url\":\"ht" +
                "tp:\\/\\/www.baidu.com\",\"fromIcon\":\"\",\"re" +
                "port_url\":\"http:\\/\\/kf.qq.com\\/faq\\/180522RRRVvE180" +
                "522NzuuYB.html\",\"bannerLink\":\"\",\"fromName\":\"name\",\"" +
                "bannerImg\":\""+icon1+"\",\"bannerTxt\":\"%s\",\"item1Img\":\"\"}}}";

        return String.format(json,new Object[]{title,text});
    }
    static String a(String str){
        log("log>>>>"+str);
        return str;
    }
    //签到时间
    public static String  getDate() {
        Long timeStamp = System.currentTimeMillis();  //获取当前时间戳
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));      // 时间戳转换成时间
        return sd==null?"0":sd;
    }
    //签到时间
    public static String  getDate2() {
        Long timeStamp = System.currentTimeMillis();  //获取当前时间戳
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));      // 时间戳转换成时间
        return sd==null?"0":sd;
    }
    //签到时间
    public static long  getNewYear() {
        Long timeStamp = System.currentTimeMillis();  //获取当前时间戳
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHH");
        String sd = sdf.format(new Date(timeStamp));      // 时间戳转换成时间
        return new Long(sd);
    }    //签到时间
    public static long  getHour() {
        Long timeStamp = System.currentTimeMillis();  //获取当前时间戳
        SimpleDateFormat sdf=new SimpleDateFormat("HH");
        String sd = sdf.format(new Date(timeStamp));      // 时间戳转换成时间
        return new Long(sd);
    }
    public static int getTime(int a){
        return new Integer(getDate());
    }
    //签到时间
    public static int  intDate() {
        Long timeStamp = System.currentTimeMillis();  //获取当前时间戳
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        String sd = sdf.format(new Date(Long.parseLong(String.valueOf(timeStamp))));      // 时间戳转换成时间
        return sd==null?0:new Integer(sd);
    }
    public static String getSong(String name) {
//        System.err.println("查找"+name);
        String result = "";
        BufferedReader in = null;
        try {
            System.out.println(">>"+ URLEncoder.encode(name, "utf-8"));
            URL realUrl = new URL("http://y.313u.cn/search.jsp?bid=135465&type=qq&n=1&name="+ URLEncoder.encode(name, "utf-8"));
            // �򿪺�URL֮�������
            URLConnection connection = realUrl.openConnection();
            // ����ͨ�õ���������
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // ����ʵ�ʵ�����
            connection.connect();
            // ��ȡ������Ӧͷ�ֶ�
            Map<String, List<String>> map = connection.getHeaderFields();
            // �������е���Ӧͷ�ֶ�
            // ���� BufferedReader����������ȡURL����Ӧ
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("����GET��������쳣��" + e);
            e.printStackTrace();
        }
        // ʹ��finally�����ر�������
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        try {
            System.out.println(result);
            return result;
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }return "";
    }
    public static String getSongURL(String key) {
//        System.err.println("查找"+name);{"id":"002gcmH12Ebti0","t":1}
        String result = "";
        BufferedReader in = null;
        try {
            System.out.println(">>"+ URLEncoder.encode(key, "utf-8"));
            URL realUrl = new URL("https://y.313u.cn/app/1.6/musics_1.560v.jsp?s="+ TeaUtil.e("{\"id\":\""+key+"\",\"t\":1}"));
            // �򿪺�URL֮�������
            URLConnection connection = realUrl.openConnection();
            // ����ͨ�õ���������
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // ����ʵ�ʵ�����
            connection.connect();
            // ��ȡ������Ӧͷ�ֶ�
            Map<String, List<String>> map = connection.getHeaderFields();
            // �������е���Ӧͷ�ֶ�
            // ���� BufferedReader����������ȡURL����Ӧ
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("����GET��������쳣��" + e);
            e.printStackTrace();
        }
        // ʹ��finally�����ر�������
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        try {
            System.err.println(result);
            return ZipUtil.gunzip(result.replaceAll(" ","")
                    .replaceAll("\n","")
                    .replaceAll("\t",""));
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }return "";
    }
    public static String getifun() {
        String result = "";
        BufferedReader in = null;
        try {
//            System.out.println(">>"+urlNameString);
            URL realUrl = new URL("https://api.vvhan.com/api/xh?type=json");
            // �򿪺�URL֮�������
            URLConnection connection = realUrl.openConnection();
            // ����ͨ�õ���������
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // ����ʵ�ʵ�����
            connection.connect();
            // ��ȡ������Ӧͷ�ֶ�
            Map<String, List<String>> map = connection.getHeaderFields();
            // �������е���Ӧͷ�ֶ�
            // ���� BufferedReader����������ȡURL����Ӧ
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("����GET��������쳣��" + e);
            e.printStackTrace();
        }
        // ʹ��finally�����ر�������
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        try {
            return JSON.parseObject(result).getString("joke");
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }return "";
    }
    public static String getSubUtil1(String soap, String rgex) {
        Matcher m = Pattern.compile(rgex).matcher(soap);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }
    public static boolean kouYueBi(String qq, int a, Configuration configuration){
        try{
            //System.err.println("进了");
//            int a=10;
            int b=0;
            SessionFactory sessionFactory = configuration.buildSessionFactory();
            Session session=sessionFactory.openSession();
            // System.err.println("进了0");
            String h= new StringBuilder().append("From User u where u.qq='").append(qq).append("'").toString();
            List<UserEntry> u= session.createQuery(h).list();
            UserEntry u0=null;
            // System.err.println("进了1");
            if(u==null||u.size()==0) {
                u0=new UserEntry();
                u0.setM(100);
                u0.setQq(qq+"");
                u0.setQiandao(0);
                u0.setQun("0");
                b=100;
                session.save(u0);
                session.beginTransaction().commit();
            }else {
                u0=u.get(0);
                u0.setM(u0.getM()+a);
//                if(){}
                b=u0.getM();
                if(u0.getM()<500){
                    session.clear();
                    session.close();
                    sessionFactory.close();
                    return false;
                }
                session.update(u0);
                session.beginTransaction().commit();

            }
            System.err.println(u0.toString());
            session.clear();
            session.close();
            sessionFactory.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
        //sender.SENDER.sendGroupMsg(msg, "签到失败，请等会再试试");

    }
//    public static boolean printLog(Session session, YJiLu y){
//        session.
//    }

    /**
     * 年月日 可读性时间
     * @return
     */
    public static  String getTime(){
        Date date = new Date(); // this object contains the current date value
//        上面获取到的日期也可以被format成我们需要的格式，例如：

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }    /**
     * 年月日 可读性时间
     * @return
     */
    public static  String todate(){
        Date date = new Date(); // this object contains the current date value
//        上面获取到的日期也可以被format成我们需要的格式，例如：

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }
    public static String daJie(JiLuEntry yJiLu, Configuration config){
        try{
            int b=0;
            SessionFactory sessionFactory = config.buildSessionFactory();
            Session session=sessionFactory.openSession();
            // System.err.println("进了0");
            String h= new StringBuilder().append("From User u where u.qq='").append(yJiLu.getQq0()).append("'").toString();//获取自己
            List<UserEntry> u= session.createQuery(h).list();
            String h1= new StringBuilder().append("From User u where u.qq='").append(yJiLu.getQq1()).append("'").toString();//获取别人
            List<UserEntry> uu= session.createQuery(h1).list();
            UserEntry u0=null,u1=null;
            // System.err.println("进了1");
            if(u==null||u.size()==0||uu==null||uu.size()==0) {
                return "抢劫失败，存在一方未查到数据";
            }else {

                u0=u.get(0);
                u1=uu.get(0);
                yJiLu.setQ0n(u0.getM());
                yJiLu.setQ1n(u1.getM());
                if(u0.getM()<=0||u1.getM()<=0){
                    session.clear();
                    session.close();
                    sessionFactory.close();
                    return "有一方的悦币数为0，不可抢劫";
                }
                boolean b1=yJiLu.getQq1().equals("2036085374");
                int num=(int)((Math.random()*(Math.sqrt(u1.getM()/30)+5)*100/200)+0.5);
                if(b1){
                    //活动
                    if(num==0)num=5;

                    double r=Math.random()*10;
                    System.err.println(num+"n>"+yJiLu.getN()+"<><>"+r);
                    if(r<6&&Math.random()*10<9){

                        yJiLu.setN(num);
                    }else{
                        yJiLu.setN(num>10?-num/2:-num);
                    }
                }else{
                    if(num==0)num=2;
                    double r=Math.random()*10;
                    System.err.println(num+"n>"+r);
                    if(r<6&&Math.random()*10<9){
                        yJiLu.setN(num);
                    }else{
                        yJiLu.setN(num>10?-num/2:-num);
                    }
                }
                u0.setM(u0.getM()+yJiLu.getN());
                u1.setM(u1.getM()-yJiLu.getN());
                b=u0.getM();
                session.save(yJiLu);
                session.update(u0);
                session.update(u1);
                session.beginTransaction().commit();

            }
            // System.err.println(u0.toString());
            session.clear();
            session.close();
            sessionFactory.close();
            return yJiLu.getN()>0?"抢劫成功，获得"+yJiLu.getN()+"悦币\n你当前悦币数 "+ b:"抢劫失败，你被抢"+-yJiLu.getN()+"悦币\n你当前悦币数 "+b;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "抢劫异常";
        //sender.SENDER.sendGroupMsg(msg, "签到失败，请等会再试试");

    }
    public static String zengSong(JiLuEntry yJiLu,Configuration config){
        try{
            int b=0;
            SessionFactory sessionFactory = config.buildSessionFactory();
            Session session=sessionFactory.openSession();
            // System.err.println("进了0");
            String h= new StringBuilder().append("From User u where u.qq='").append(yJiLu.getQq0()).append("'").toString();//获取自己
            List<UserEntry> u= session.createQuery(h).list();
            String h1= new StringBuilder().append("From User u where u.qq='").append(yJiLu.getQq1()).append("'").toString();//获取别人
            List<UserEntry> uu= session.createQuery(h1).list();
            UserEntry u0=null,u1=null;
            // System.err.println("进了1");
            if(u==null||u.size()==0||uu==null||uu.size()==0) {
                return "赠送失败，存在一方未查到数据";
            }else {
                u0=u.get(0);
                u1=uu.get(0);
                yJiLu.setQ0n(u0.getM());
                yJiLu.setQ1n(u1.getM());
                b=u0.getM();
                if(u0.getM()<500){
                    session.clear();
                    session.close();
                    sessionFactory.close();
                    return "你的悦币余额小于500\n不可以赠送哦\n当前悦币数 "+b;
                }
                if(!(yJiLu.getQq1().equals("1054980699"))){
                    u0.setM(u0.getM()+yJiLu.getN());
                }

                u1.setM(u1.getM()-yJiLu.getN());

                System.err.println(yJiLu);
                b=u0.getM();

                if(u0.getM()<0||u1.getM()<0){
                    session.clear();
                    session.close();
                    sessionFactory.close();
                    return "你的悦币不够哦\n当前悦币数 "+b;
                }
                session.save(yJiLu);
                session.update(u0);
                session.update(u1);
                session.beginTransaction().commit();

            }
            // System.err.println(u0.toString());
            session.clear();
            session.close();
            sessionFactory.close();
            return "赠送成功，"+yJiLu.getQq1()+"获得 "+-yJiLu.getN()+" 悦币\n你当前悦币数 "+b;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "赠送异常";
        //sender.SENDER.sendGroupMsg(msg, "签到失败，请等会再试试");

    }

    public static boolean isGuoqing() {
        return getTime(0)<20201010&&getTime(0)>=20201001;
    }
    public static boolean isChuXi(){
        return getTime(0)==20230121;
    }
    public static boolean is8点(){
        return getNewYear()>=2023012120;
//        return getNewYear()>=2021020515;
    }
    public static boolean is端午8点(){
        return getNewYear()>=2022013120;
//        return getNewYear()>=2021020515;
    }

    public static boolean is过年() {
        return getTime(0)>=20210208&&getTime(0)<20210218;
    }
    public static boolean is年初() {
        return getTime(0)>=20210211&&getTime(0)<20210218;
    }

    public static String getDateString() {
        Date date = new Date(); // this object contains the current date value
//        上面获取到的日期也可以被format成我们需要的格式，例如：

        SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日 晴\n");
        return formatter.format(date);
    }

    public static boolean is51() {
        return getTime(0)>=20210501&&getTime(0)<20210615;
    }

    public static String getkuWoSongURL(String key) {
        //        System.err.println("查找"+name);{"id":"002gcmH12Ebti0","t":1}
        String result = "";
        BufferedReader in = null;
        try {
            System.out.println(">>"+ URLEncoder.encode(key, "utf-8"));
            URL realUrl = new URL("http://121.196.47.176:8096/v1/download/musics?s="+ URLEncoder.encode(TeaUtil.e("{\"br\":4,\"d\":\""+key.split("_")[1]+"\",\"mt\":2}"),"UTF-8"));
            // �򿪺�URL֮�������
            URLConnection connection = realUrl.openConnection();
            // ����ͨ�õ���������
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            // ����ʵ�ʵ�����
            connection.connect();
            // ��ȡ������Ӧͷ�ֶ�
            Map<String, List<String>> map = connection.getHeaderFields();
            // �������е���Ӧͷ�ֶ�
            // ���� BufferedReader����������ȡURL����Ӧ
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(),"utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("����GET��������쳣��" + e);
            e.printStackTrace();
        }
        // ʹ��finally�����ر�������
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        try {
            System.err.println(result);
            return result;
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }return "";
    }

    public static boolean get2022端午() {
//        return true;
        return getTime(0)>=20220603&&getTime(0)<=20220605;
    }

    public static boolean randomBool() {
        return Math.random()*10>6;
    }

    public static boolean randomBoolAnd端午() {
        return get2022端午()&&randomBool();
    }
}
